package birdsong.filter;

import java.util.ArrayList;

public class MonitorExcessMessage extends Monitor {

	public MonitorExcessMessage(double timeout, int nMaxDisconnect, int nMaxWarning) {
		super(timeout, nMaxDisconnect, nMaxWarning);
	}

	/*
	 * Checks if the monitor receives in an interval <timeout>
	 * The number of messages <nMaxWarning> represents the number 
	 * of received messages needed to send a warning to the user
	 * Use it to check and insert the message in the queue
	 */
	
	/**
	 * @return true if the monitor received <nMaxWarning> messages 
	 * in less than <timeout>
	 */
	@Override
	public boolean sendWarning() {
		ArrayList<Message> messageList = getList();
		int sizeList = messageList.size();
		int nOccurrences = 0;
		Message key = messageList.get(sizeList - 1);
		Message test;
		if(sizeList >= getNMaxWarning()){
			for(int i = sizeList-2; i >= 0 ; i--){
				test = messageList.get(i);
				if(((key.getDate()-test.getDate())<getTimeout()))
					nOccurrences++;
			}
		}
		
		if(nOccurrences + 1 == getNMaxWarning())
			return true;

		return false;
	}

	/*
	 * Checks if the monitor receives in an interval <timeout>
	 * The number of messages <nMaxWarning> represents the number 
	 * of received messages needed to disconnect the user
	 * Use it to check and insert the message in the queue
	 */
	
	/**
	 * @return true if the monitor received <nMaxWarning> messages 
	 * in less than <timeout>
	 */
	@Override
	public boolean disconnectClient() {
		ArrayList<Message> aux = getList();
		int sizeList = aux.size();
		int nOccurrences = 0;
		Message key = aux.get(sizeList-1);
		Message test;
		if(sizeList >= getNMaxDisconnect()){
			for(int i = sizeList-2; i >= 0;i--){
				test = aux.get(i);
				if(((key.getDate() - test.getDate()) < getTimeout()))
					nOccurrences++;
			}
		}
		if(nOccurrences + 1 == getNMaxDisconnect())
			return true;

		return false;
	}

}
